package cn.sample.moreitems.event;

import cn.sample.moreitems.MoreItems;
import cn.sample.moreitems.init.ModItems;
import cn.sample.moreitems.item.XuanyuanSwordItem;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.damagesource.DamageSource;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.monster.Zombie;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraftforge.event.entity.living.LivingAttackEvent;
import net.minecraftforge.event.entity.living.LivingHurtEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;

@Mod.EventBusSubscriber(modid = MoreItems.MODID, bus = Mod.EventBusSubscriber.Bus.FORGE)
public class CombatEvents {

    /**
     * 每当一个 LivingEntity 即将受到伤害时都会走这里
     * 此时伤害源已经生成，但血量还没扣
     */
    @SubscribeEvent
    public static void onLivingAttacked(LivingHurtEvent event) {
        LivingEntity target = event.getEntity();          // 被打的人
        DamageSource source = event.getSource();          // 伤害源
        Entity directEntity = source.getDirectEntity();   // 直接造成伤害的实体（通常是玩家）
        Entity attacker = source.getEntity();             // 攻击者（也是玩家）

        // 1. 只关心玩家近战
        if (!(attacker instanceof ServerPlayer player)) return;

        // 2. 拿到主手武器
        ItemStack weapon = player.getMainHandItem();
        XuanyuanSwordItem xuanYuan = ModItems.XUAN_YUAN_SWORD_ITEM.get();
        if (weapon.is(xuanYuan)) {
            // 4. 计算新伤害：目标最大生命值的 10%
            float newDamage = target.getMaxHealth() * 0.1f;
            // 5. 重新设伤害值（向下取整到 0.5 也可自己调）
            event.setAmount(newDamage);
            xuanYuan.getAttr().compute(target, (k, v) -> {
                if (v == null) {
                    return 0;
                } else if (v == 2) {
                    event.setAmount(target.getMaxHealth() * 0.7f);
                    v = 0;
                } else {
                    return v + 1;
                }
                return v;
            });
        }
    }

}
